package 合并两个有序链表;


/**
 * @author 冷加宝
 * @version 1.0
 */
public class MergeTwoLists {

    public static class ListNode{
        int val;
        ListNode next;
        public ListNode(int val){
            this.val = val;
        }

        public ListNode(int val, ListNode next){
            this.val = val;
            this.next = next;
        }
    }

    public static ListNode mergeTwoLists(ListNode Head1, ListNode Head2){
        if(Head1 == null || Head2 == null){
            return Head1 == null ? Head2 : Head1;
        }

        ListNode head = Head1.val <= Head2.val ? Head1 : Head2;
        ListNode cur1 = head.next;
        ListNode cur2 = head == Head1 ? Head2 : Head1;
        ListNode pre = head;
        while(cur1 != null && cur2 != null){
            if(cur1.val <= cur2.val){
                pre.next = cur1;
                cur1 = cur1.next;
            }else{
                pre.next = cur2;
                cur2 = cur2.next;
            }
            pre = pre.next;
        }

        pre.next = cur1 == null ? cur2 : cur1;
        return head;
    }
}
